/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.srgsxmldb.servlets;


import cz.muni.fi.pb138.srgsxmldb.manager.IXManager;
import cz.muni.fi.pb138.srgsxmldb.manager.XManager;
import cz.muni.fi.pb138.srgsxmldb.validator.ValidatorSRGS;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;




/**
 * This class provides functionality for uploading xml srgs grammars
 * 
 * @author Eldred
 */
public class UploadServlet extends HttpServlet{
    
    private ValidatorSRGS validator;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
            doPost(request, response);
    }

    /**
     * adds uploaded grammar file to database. In case of failure informs the user.
     * @param request
     * @param response
     * @throws IOException 
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setContentType("text/html");

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            Document doc = null;
            ProcessFailures failure = ProcessFailures.NONE;

            List<FileItem> fields = null;              
            try {

                fields = upload.parseRequest(request);

            } catch (FileUploadException ex) {
                Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            Iterator<FileItem> it = fields.iterator();
            FileItem file = it.next();

            if (file.isFormField()) {

                failure = ProcessFailures.ISFIELD;
            }
            else {

                DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder;
                
 
                fact.setNamespaceAware(true);
                fact.setValidating(false);

                try {

                    builder = fact.newDocumentBuilder();
                    doc = builder.parse(file.getInputStream()); 

                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SAXException ex) {
                    Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (doc == null) {
                    failure = ProcessFailures.NOTWELLFORMED;
                }
                else {
                    validator = new ValidatorSRGS();
                    if(!validator.validate(doc)) {
                        failure = ProcessFailures.NOTSRGS;
                    }
                    else {
                        IXManager manager = new XManager();                   
                        manager.addGrammarFromXMLFile(file);
                    }

                }
            }

            request.setAttribute("failure", failure);
            request.setAttribute("file", file);
            request.setAttribute("requestedContent", "/upload");

            try {
                request.getRequestDispatcher("/index").include(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
}
